<template>
  <a-modal
    width="100%"
    :visible='editVisible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    :style="{ top: '0px' }"
    @update:visible='updateEditVisible'
    :footer="null"
  >
    <div class='ele-body ele-body-card'>
      <!-- 顶部卡片 -->
      <a-card
        :bordered='true'
        :body-style="{padding: '20px'}">
        <a-form
          ref='form'
          :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
          :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
          @submit='pushSubmitConfigSubmit'
        >
          <a-divider orientation="left">围栏配置</a-divider>
          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='围栏名字:' name='geofenceName'>
                <a-input v-model:value='form.geofenceName' style="width: 180px" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24' />
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label="Model:" name="geoMode">
                <a-select v-model:value="form.geoMode">
                  <a-select-option :value="0">Disable</a-select-option>
                  <a-select-option :value="2">Exiting the zone</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='Start-Eed Point:' name='startPoint'>
                Start:<a-input-number :disabled="true" :min="1" :max="10" v-model:value='form.startPoint'  allow-clear @change="startPointChange" />
                End:<a-input-number :min="3" :max="10" v-model:value='form.endPoint' allow-clear @change="endPointChange" />

                <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='selectMapAction'>地图选择位置</a-button>
              </a-form-item>
            </a-col>

            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>
          <a-divider orientation="left">Points Setting</a-divider>
          <a-row :gutter='8'>
            <a-col :md='24' :sm='24' :xs='24'>
              <div>
                <VehicleManagerGeofenceRanchManagerFencelistSubpoint v-for="(item, index) in pointObjs"
                                                            :key="index" :index="index" :point="item"

                />
              </div>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='2' :sm='24' :xs='24'>
            </a-col>
            <a-col :md='8' :sm='24' :xs='24'>
              <a-button type='primary' html-type='submit'>
                提交
              </a-button>
            </a-col>
            <a-col :md='8' :sm='24' :xs='24'>
            </a-col>
            <a-col :md='6' :sm='24' :xs='24'></a-col>
          </a-row>
        </a-form>
      </a-card>
      <VehicleManagerGeofenceRanchManagerFencelistBmap v-if="showSelectPoint" v-model:visible="showSelectPoint" :path="currentPath" @done="fillPoint" />
    </div>
  </a-modal>
</template>

<script>

import { message } from 'ant-design-vue';
import VehicleManagerGeofenceRanchManagerFencelistSubpoint from './ranchfence-fencelist-subpoint.vue'
import VehicleManagerGeofenceRanchManagerFencelistBmap from './ranchfence-fencelist-bmap.vue'
import {VehicleGeofencePolygonRanchApi} from "@/api/property/vechile/VehicleGeofencePolygonRanchApi";

export default {
  name: 'VehicleManagerGeofenceRanchManagerFencelistEdit',
  components: {
    VehicleManagerGeofenceRanchManagerFencelistSubpoint,
    VehicleManagerGeofenceRanchManagerFencelistBmap
  },
  emits: ['done', 'update:editVisible'],
  props: {
    // 弹窗是否打开
    editVisible: Boolean,
    // 修改回显的数据
    data: Object,
    ranchData : Object
  },
  mounted() {
    if (this.data) {
      this.form = Object.assign({}, this.data);
      this.isUpdate = true;
      if (this.form.points) {
        let points =  JSON.parse(this.form.points);
        if (points.length > 0) {
          this.form.startPoint = 1;
          this.form.endPoint = points.length;
          this.pointObjs = points;
        } else {
          this.form.startPoint = 1;
          this.form.startPoendPointint = 3;
          this.pointObjs = [];
        }
      } else {
        this.form.startPoint = 1;
        this.form.endPoint = 3;
        this.pointObjs = [];
      }
    } else {
      this.form = {
        startPoint : 1,
        endPoint : 3
      };
      this.pointObjs = [];
      this.isUpdate = false;
    }
    if (this.pointObjs.length === 0) {
      let startPoint = this.form.startPoint;
      let endPoint = this.form.endPoint;
      for (;startPoint<=endPoint;startPoint++) {
        this.pointObjs.push({
          "index" : startPoint,
          "latitude" : "",
          "longitude" : "",
          "bd_latitude" : "",
          "bd_longitude" : "",
          "gcj_latitude" : "",
          "gcj_longitude" : ""
        });
      }
    }
    if (this.$refs.form) {
      this.$refs.form.clearValidate();
    }
  },
  data() {
    return {
      form : {},
      pointObjs : [],
      loading : false,

      showSelectPoint : false,
      currentPath : [],
      // 是否是修改
      isUpdate: false,
    };
  },
  methods: {
    fillPoint(path) {
      console.log("子页面回调")
      if (path && path.length > 0) {
        let points = [];
        for(let i = 0; i< path.length; i ++) {
          points.push({
            "index" : i + 1,
            "bd_latitude" : parseFloat("" + path[i].lat).toFixed(6),
            "bd_longitude" : parseFloat("" + path[i].lng).toFixed(6),
            "gcj_latitude" : "",
            "gcj_longitude" : "",
            "latitude" : "",
            "longitude" : ""
          });
        }
        this.pointObjs = points;
        this.form.startPoint = 1;
        this.form.endPoint = path.length;
      }
    },
    selectMapAction () {
      console.log(111);
      this.currentPath = JSON.parse(JSON.stringify(this.pointObjs));
      this.showSelectPoint = true;
    },

    startPointChange(value) {
      if (value == undefined || value == '' || value < 1 || value > 10) {
        message.error('只能输入0-10的数字');
      } else {
        let endPoint = this.form.endPoint;
        if (value > endPoint) {
          this.form.endPoint = value;
        }
        let sourcePointObjs = [];
        this.pointObjs.forEach(function(item) {
          sourcePointObjs[item.index] = item;
        });
        let destPoints = [];
        for (let i = value;i <= this.form.endPoint;i++) {
          if (undefined != sourcePointObjs[i]) {
            destPoints.push(sourcePointObjs[i]);
          } else {
            destPoints.push({
              "index": i,
              "latitude": "",
              "longitude": "",
              "bd_latitude" : "",
              "bd_longitude" : "",
              "gcj_latitude" : "",
              "gcj_longitude" : ""
            });
          }
        }
        this.pointObjs = destPoints;
      }
    },
    endPointChange(value){
      if (value == undefined || value == '' || value < 3 || value > 10) {
        message.error('只能输入0-10的数字');
      } else {
        let startPoint = this.form.startPoint;
        if (value < startPoint) {
          this.form.startPoint = value;
        }
        let sourcePointObjs = [];
        this.pointObjs.forEach(function(item) {
          sourcePointObjs[item.index] = item;
        });
        let destPoints = [];
        for (let i = this.form.startPoint;i <= this.form.endPoint;i++) {
          if (undefined != sourcePointObjs[i]) {
            destPoints.push(sourcePointObjs[i]);
          } else {
            destPoints.push({
              "index": i,
              "latitude": "",
              "longitude": "",
              "bd_latitude" : "",
              "bd_longitude" : "",
              "gcj_latitude" : "",
              "gcj_longitude" : ""
            });
          }
        }
        this.pointObjs = destPoints;
      }
    },

    pushSubmitConfigSubmit() {
      let that = this;
      let formResult = null;
      that.form.points = JSON.stringify(that.pointObjs);
      that.form.ranchId = that.ranchData.ranchId;
      that.loading = true;
      if (that.isUpdate) {
        formResult = VehicleGeofencePolygonRanchApi.edit(that.form);
      } else {
        formResult = VehicleGeofencePolygonRanchApi.add(that.form);
      }
      formResult
        .then(result => {
          that.loading = false;
          message.success(result.message);
          // 关闭弹框，通过控制visible的值，传递给父组件
          that.updateEditVisible(false);
          // 触发父组件done事件
          that.$emit('done');
        })
        .catch(() => {
          that.loading = false;
        });
    },

    updateEditVisible(value) {
      this.$emit('update:editVisible', value);
    },
  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
